(function () {
    const SELECTOR = 'select#jobGroup, select[name=\"jobGroup\"]';
    const ENHANCED_FLAG = 'jobGroupEnhanced';

    const enhanceJobGroupSelect = (select) => {
        if (!select || select.dataset[ENHANCED_FLAG] === 'true') {
            return;
        }

        select.dataset[ENHANCED_FLAG] = 'true';

        const wrapper = document.createElement('div');
        wrapper.style.position = 'relative';
        wrapper.style.width = '100%';

        const input = document.createElement('input');
        input.type = 'text';
        input.placeholder = '请输入关键词过滤任务...';
        input.style.width = '100%';
        input.style.boxSizing = 'border-box';
        input.style.padding = '6px';
        input.style.marginBottom = '4px';
        input.style.border = '1px solid #ccc';
        input.style.borderRadius = '4px';

        const suggestionBox = document.createElement('div');
        suggestionBox.style.position = 'absolute';
        suggestionBox.style.left = '0';
        suggestionBox.style.right = '0';
        suggestionBox.style.border = '1px solid #ddd';
        suggestionBox.style.borderTop = 'none';
        suggestionBox.style.maxHeight = '200px';
        suggestionBox.style.overflowY = 'auto';
        suggestionBox.style.background = '#fff';
        suggestionBox.style.zIndex = '9999';
        suggestionBox.style.display = 'none';
        suggestionBox.style.boxSizing = 'border-box';

        const parent = select.parentNode;
        parent.insertBefore(wrapper, select);
        wrapper.appendChild(input);
        wrapper.appendChild(suggestionBox);
        wrapper.appendChild(select);

        const syncInputWithSelect = () => {
            const option = select.options[select.selectedIndex];
            input.value = option ? option.text : '';
        };

        syncInputWithSelect();

        const hideSuggestions = () => {
            suggestionBox.style.display = 'none';
        };

        const repositionBox = () => {
            suggestionBox.style.top = input.offsetHeight ? input.offsetHeight + 'px' : '36px';
        };

        const renderSuggestions = (keyword) => {
            const kw = keyword.trim().toLowerCase();
            const options = Array.from(select.options).map((opt) => ({
                text: opt.text,
                value: opt.value
            }));

            suggestionBox.innerHTML = '';
            repositionBox();

            if (!kw) {
                hideSuggestions();
                return;
            }

            const matched = options.filter((opt) => opt.text.toLowerCase().includes(kw));

            if (matched.length === 0) {
                hideSuggestions();
                return;
            }

            matched.forEach((opt) => {
                const item = document.createElement('div');
                item.textContent = opt.text;
                item.style.padding = '6px 10px';
                item.style.cursor = 'pointer';

                item.addEventListener('mouseenter', () => {
                    item.style.background = '#f0f0f0';
                });

                item.addEventListener('mouseleave', () => {
                    item.style.background = '';
                });

                item.addEventListener('click', () => {
                    select.value = opt.value;
                    select.dispatchEvent(new Event('change', { bubbles: true }));
                    syncInputWithSelect();
                    hideSuggestions();
                    select.focus();
                });

                suggestionBox.appendChild(item);
            });

            suggestionBox.style.display = 'block';
        };

        input.addEventListener('input', (event) => {
            renderSuggestions(event.target.value);
        });

        input.addEventListener('focus', () => {
            if (input.value.trim()) {
                renderSuggestions(input.value);
            }
        });

        select.addEventListener('change', syncInputWithSelect);

        document.addEventListener('click', (event) => {
            if (!wrapper.contains(event.target)) {
                hideSuggestions();
            }
        });

        window.addEventListener('resize', repositionBox);
    };

    const observeJobGroupSelect = () => {
        const observer = new MutationObserver((mutations) => {
            mutations.forEach((mutation) => {
                mutation.addedNodes.forEach((node) => {
                    if (node.nodeType !== Node.ELEMENT_NODE) {
                        return;
                    }

                    if (node.matches && node.matches(SELECTOR)) {
                        enhanceJobGroupSelect(node);
                        return;
                    }

                    if (node.querySelectorAll) {
                        node.querySelectorAll(SELECTOR).forEach((select) => {
                            enhanceJobGroupSelect(select);
                        });
                    }
                });
            });
        });

        observer.observe(document.body, {
            childList: true,
            subtree: true
        });
    };

    const init = () => {
        document.querySelectorAll(SELECTOR).forEach((select) => {
            enhanceJobGroupSelect(select);
        });
        observeJobGroupSelect();
        console.log('[plugin] jobGroup 搜索增强已启用');
    };

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }
})();
